package com.luozy.item.interceptor;

import com.luozy.common.context.TrdLocal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//自定义拦截器
@Slf4j
@Component
public class ItemInterceptor implements HandlerInterceptor {

    //目标资源方法执行前执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头中的用户id
        String userId = request.getHeader("authorization");
        //存入ThreadLocal
        TrdLocal.threadLocal.set(Long.valueOf(userId));
        log.info("登录用户id：{}", TrdLocal.threadLocal.get());
        //放行
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("...目标方法已执行");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("...视图渲染完毕");
    }
}
